<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Admin;
use App\Model\Adv;
use App\Model\Advcontent;
use App\Model\Category;
use App\Model\Content;
use App\Server\JwtServer;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
  // 登录
  public function login(Request $request)
  {
    // 设置验证规则
    $rule = [
      'username' => 'required|min:3|max:5',
      'password' => 'required|min:6|max:12'
    ];
    // 设置验证信息
    $message = [
      'username.required' => '用户名不能为空',
      'username.min' => '密码长度在 3 到 5 个字符',
      'username.max' => '密码长度在 3 到 5 个字符',
      'password.required' => '密码不能为空',
      'password.min' => '密码长度在 6 到 12 个字符',
      'password.max' => '密码长度在 6 到 12 个字符'
    ];
    $validator = Validator::make($request->all(), $rule, $message);
    if ($validator->fails()) {
      foreach ($validator->getMessageBag()->toArray() as  $v) {
        $msg = $v[0];
      }
      return response()->json(['status' => 400, 'msg' => $msg]);
    }
    $username = $request->get('username');
    $password = $request->get('password');

    // 根据用户名获取数据库信息
    $userInfo = Admin::where('username', $username)->first();
    // 判断用户是否存在
    if (!$userInfo) return response()->json(['status' => 400, 'msg' => '用户不存在！',]);
    // 判断密码是否正确
    if (md5(md5($password) . $userInfo->salt) !== $userInfo->password)
      return response()->json(['status' => 400, 'msg' => '密码错误！']);

    // 生成token
    $token = JwtServer::createToken($userInfo->id);

    return response()->json(['status' => 200, 'token' => $token, 'msg' => '登录成功！']);
  }
}
